import { login, logout, getInfo } from '@/api/sys/login'

import { getToken, setToken, removeToken, setRealname } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// import store from '@/store'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  resources: []// 当前用户对应的可以展示的权限
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_RESOURCES: (state, resources) => {
    state.resources = resources
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.accessToken) // vuex设置token的值
        localStorage.setItem('accessToken', data.accessToken) // localstorage设置token
        // setToken(data.accessToken)// 设置登录后获取的token
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ token: state.token }).then(response => {
        const { data } = response
        localStorage.setItem('userResources', response.data.userResources)// 获取用户对应的资源
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        var rolesSet = data.roleIds.split('@')
        data.roles = rolesSet
        // const { roles, authos, name, avatar, introduction } = data
        const { name, avatar, introduction } = data
        var resources = data.userResources.split('@')
        // roles must be a non-empty array
        // if (!roles || roles.length <= 0) {
        //   reject('getInfo: roles must be a non-null array!')
        // }
        // commit('SET_ROLES', roles)
        console.log('rolesSet' + rolesSet)
        commit('SET_ROLES', rolesSet)
        commit('SET_RESOURCES', resources)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        // console.log('获取：' + store.getters.resources)
        setRealname(response.data.realName) // 设置用户姓名
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout({ 'token': state.token }).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_RESOURCES', [])
        // commit('SET_AUTHOS', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      // commit('SET_AUTHOS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
